<!-- p_purchase.ftl 采购单 -->
var Msales = {
    u: '/mSales',
    uList: '/mSales/list',
    uEdit: '/mSales/doEdit',
    editIndex: -1,
    unitArr: [],
    isDg: 0,
    winThat: undefined,
    dgType: undefined
};

$.extend($.fn.datagrid.defaults.editors, {
    house: {
        init: function (container, options) {
            return $('<div style="text-align: center">编辑</div>').appendTo(container);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            var rows = Msales.dtable.datagrid("getRows");
            var house = rows[Msales.editIndex].house;
            return house;
        },
        setValue: function (target, value) {
        },
        resize: function (target, width) {
            $(target).click(function () {
                Msales.isDg = 1;
                var rows = Msales.dtable.datagrid("getRows");
                var skuId = rows[Msales.editIndex].skuId;
                var house = rows[Msales.editIndex].house;
                // var href = "/wWearhouse/treeGrid?skuId=" + skuId + "&house=" + house + "&type=0";//type 0出库 1入库
                var href = "/wWearhouse/outNewVersion?skuId=" + skuId ;//type 0出库 1入库
                var $dg = $yd.win.create('仓库/库位/批次', href);
                $dg.width = "450px;";
                $dg.height = "520px;";
                $dg.open(function (that, $win) {
                    Msales.winThat = that;
                    Msales.dgType = "house";
                }, function (that, $win) {
                    Msales.saveDgHouse();
                }, function () {
                    if (Msales.editIndex > -1) {
                        Msales.dtable.datagrid('endEdit', Msales.editIndex);
                    }
                    Msales.editIndex = -1;
                    Msales.isDg = 0;
                    Msales.winThat = undefined;
                    Msales.dgType = undefined;
                });
            });

            $(target)._outerWidth(width);
        }
    }
});
Msales.saveDgHouse = function () {
    var rows = Msales.dtable.datagrid("getRows");
    var data = KW.getResult();
    if (data != "error") {
        if (data != "") {
            //销售数量也要修改
            var arr = data.split(",");
            var total = 0;
            for (var i = 0; i < arr.length; i++) {
                total += Number(arr[i].split("_")[6]);
            }
            if (total == Number(rows[Msales.editIndex].count)) {
                Msales.dtable.datagrid('updateRow', {
                    index: Msales.editIndex,
                    row: {
                        house: data
                    }
                });
            } else {
                Msales.dtable.datagrid('updateRow', {
                    index: Msales.editIndex,
                    row: {
                        house: data,
                        count: total,
                        shouldPay: Number(total) * Number(rows[Msales.editIndex].amountActual)
                    }
                });
                Msales.caculate();
            }
        } else {
            Msales.dtable.datagrid('updateRow', {
                index: Msales.editIndex,
                row: {
                    house: data
                }
            });
        }

        Msales.winThat.close();
        Msales.isDg = 0;
        Msales.winThat = undefined;
        Msales.dgType = undefined;
    }
};
Msales.dg = function () {
    Msales.dtable = $('#mSales_table');
    Msales.dtable.datagrid({
        pagination: false,
        fitColumns: true,
        autoRowHeight: true,
        rownumbers: true,
        singleSelect: false,
        toolbar: [
            {
                text: '增加（Insert）', iconCls: 'icon-add', handler: function () {
                    Msales.plus();
                }
            },
            {
                text: '删除（Del）', iconCls: 'icon-remove', handler: function () {
                    Msales.remove();
                }
            }
        ],
        columns: [[
            {field: 'skuId', checkbox: true},//规格id
            {field: 'goodsName', title: '商品名称', width: 150},
            {field: 'goodsId', title: '商品ID', width: 80, hidden: true},
            {field: 'skus', title: '规格', width: 200},

            // {
            //     field: 'house',
            //     title: '<span style="color:blue">仓库/库位/批次</span>',
            //     width: 200,
            //     editor: {type: 'house'},
            //     formatter: function (value, row, index) {
            //         if (Msales.isEmpty(value)) {
            //             return "";
            //         }
            //         var arr = value.split(",");
            //         var result = "";
            //         var first = "";
            //         for (var i = 0; i < arr.length; i++) {
            //             var arr2 = arr[i].split("_");
            //             result += arr2[1] + " " + arr2[3] + " " + arr2[4] + " X " + arr2[6] + "\n"
            //             if (first == "") {
            //                 first += arr2[1] + " " + arr2[3] + " " + arr2[4] + " X " + arr2[6];
            //             }
            //         }
            //         return "<a style='color:purple' title='" + result + "'>" + first + (arr.length > 1 ? "..." : "") + "</a>";
            //     }
            // },

            {
                field: 'amount', title: '参考售价', width: 80, formatter: function (value, row, index) {
                    return Number(value).toFixed(2);
                }
            },
            {
                field: 'amountActual',
                title: '<span style="color:blue">销售价</span><span style="color:red">*</span>',
                width: 80,
                editor: {type: 'numberbox', options: {required: true, min: 0, precision: 2}},
                formatter: function (value, row, index) {
                    return Number(value).toFixed(2);
                },
                formatter: function (value, row, index) {
                    return Number(value).toFixed(2);
                }
            },
            {
                field: 'count',
                title: '<span style="color:blue">数量</span><span style="color:red">*</span>',
                width: 80,
                editor: {type: 'numberbox', options: {required: true, min: 1, precision: 0}}
            },
            {
                field: 'shouldPay', title: '总金额', width: 80, formatter: function (value, row, index) {
                    return Number(value).toFixed(2);
                }
            },
            {field: 'skusNum', title: '库存数量', width: 80},
            {field: 'code', title: '商品编号', width: 80},
            {field: 'OECode', title: 'OE编号', width: 80},
            {
                field: 'car', title: '适用车型', width: 150, hidden:false, formatter: function (value, row, index) {
                return Msales.formatDetail(value);
            }
            },
        ]],
        onClickCell: function (index, field) {
            if (Msales.editIndex != index) {
                if (Msales.editIndex > -1) {
                    Msales.dtable.datagrid('endEdit', Msales.editIndex);
                }
                Msales.editIndex = index;
            }
            if (field == "batchCode" || field == "amountActual" || field == "count" || field == "remark" || field == "house") {
                Msales.dtable.datagrid('beginEdit', index);
            }
        },
        onEndEdit: function (index, row, changes) {
            if (changes) {
                if (changes.count != undefined && row.skusNum != 0) {
                    if (row.count > row.skusNum) {
                        Msales.dtable.datagrid('updateRow', {
                            index: index,
                            row: {
                                count: row.skusNum
                            }
                        });
                    }
                    // $yd.alert("当前批次数量不足，需重新分配出库");
                    $.post("/inRepositoryDetail/getSkuHouseByNum", {
                        skuId: row.skuId,
                        num: row.count
                    }, function (data) {
                        Msales.dtable.datagrid('updateRow', {
                            index: index,
                            row: {
                                house: data
                            }
                        });
                    });
                }

                Msales.dtable.datagrid('updateRow', {
                    index: index,
                    row: {
                        shouldPay: Number(row.amountActual) * Number(row.count)
                    }
                });
                Msales.caculate();
            }
        }
    });

    Msales.dtable.datagrid('enableCellEditing');
};
Msales.formatDetail = function (value) {
    if ($yd.isEmpty(value)) {
        return "";
    }
    var result = "";
    var first = "";
    var arr = value.split(",");
    if (arr.length == 1) {
        return "<a style='color:purple' title='" + value + "'>" + value + "</a>";
    }
    for (var i = 0; i < arr.length; i++) {
        result += arr[i] + "\n";
        if (i == 0) {
            first = result;
        }
    }
    var html = "<a style='color:purple' title='" + result + "'>" + first + "..." + "</a>";

    return html;
};
Msales.refresh = function () {
    window.location.reload();
};
Msales.changeTotalFee = function (newValue, oldValue) {
    if (newValue == "") {
        $("#totalFee").numberbox("setValue", 0);
        return;
    }
    if (Number(newValue) > Number($("#goodsFee").val())) {
        $yd.alert("应付总额不能大于商品总额！", function () {
            $("#totalFee").numberbox("setValue", $("#goodsFee").val());
        });
    } else {
        $("#discountFee").numberbox("setValue", Number($("#goodsFee").val()) - Number($("#totalFee").val()));
        if (Number(newValue) < Number($("#payFee").val())) {
            $yd.alert("本次付款金额不能大于应付总额1！", function () {
                $("#payFee").numberbox("setValue", newValue);
                $("#payedFee").numberbox("setValue", newValue);
                $("#payingFee").numberbox("setValue", 0);
            });
        } else {
            $("#payedFee").numberbox("setValue", $("#payFee").val());
            $("#payingFee").numberbox("setValue", Number(newValue) - Number($("#payFee").val()));
        }
    }
};
Msales.changePayFee = function (newValue, oldValue) {
    if (newValue == "") {
        $("#payFee").numberbox("setValue", 0);
        return;
    }
    var totalFee = Number($("#totalFee").numberbox("getValue"));
    if (Number(newValue) > totalFee) {
        $yd.alert("本次付款金额不能大于应付总额2！", function () {
            $("#payFee").numberbox("setValue", totalFee);
        });
    } else {
        $("#payedFee").numberbox("setValue", newValue);
        $("#payingFee").numberbox("setValue", totalFee - Number(newValue));
    }
};
Msales.caculate = function () {
    var rows = Msales.dtable.datagrid("getData").rows;
    var goodsFee = 0;
    var totalNUm = 0;
    for (var i = 0; i < rows.length; i++) {
        goodsFee = (Number(goodsFee) + Number(rows[i].shouldPay)).toFixed(2);
        totalNUm = Number(totalNUm) + Number(rows[i].count);
    }
    // $("#totalNum").numberbox("setValue", totalNUm);
    // $("#goodsFee").numberbox("setValue", goodsFee);
    $("#totalFee").val(goodsFee);
    $("#totalNum").val(totalNUm);
    $("#realPay").val(goodsFee);
    // $("#discountFee").numberbox("setValue", 0);
    // $("#payedFee").numberbox("setValue", 0);
    // $("#payingFee").numberbox("setValue", goodsFee);
    // $("#payFee").numberbox("setValue", 0);
};

Msales.plus = function () {
    var href = "/mMateriel/searchDg";
    var $dg = $yd.win.create('商品', href);
    $dg.width = "1050px;";
    $dg.height = "400px;";
    Msales.isDg = 1;
    $dg.open(function (that, $win) {
            Msales.winThat = that;
            Msales.dgType = "goods";
        }, function (that, $win) {
            Msales.saveDgGoods();
        }, function () {
            Msales.isDg = 0;
            Msales.winThat = undefined;
            Msales.dgType = undefined;
            document.onkeydown = Msales.keyDown;
        }
    );
};
Msales.isExist = function (rows, skusId) {
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].skusId == skusId) {
            return true;
        }
    }
    return false;
};
Msales.saveDgGoods = function () {
    document.onkeydown = Msales.keyDown;
    var data = Goods.getChecked();
    if (data.length == 0) {
        Msales.winThat.close();
        Msales.isDg = 0;
        Msales.winThat = undefined;
        Msales.dgType = undefined;
    }

    var rows = Msales.dtable.datagrid("getData").rows;
    for (var i = 0; i < data.length; i++) {
        if (!Msales.isExist(rows, data[i].skuId)) {
            Msales.dtable.datagrid('appendRow', {
                skuId: data[i].skuId,
                goodsName: data[i].goodsName,
                goodsId: data[i].goodsId,
                skus: data[i].skusName,
                code: data[i].code,
                unit: data[i].unit,
                skusNum: data[i].skusNum,
                amount: data[i].sellPrice,
                amountActual: data[i].sellPrice,
                count: 1,
                shouldPay: Number(data[i].sellPrice) * Number(1),
                house: data[i].house,
                wearhouseName: data[i].wearhouseName,
                car: data[i].car,
                OECode : data[i].partsCode

            }).datagrid('clearSelections');
        }
    }
    Msales.caculate();

    Msales.winThat.close();
    Msales.isDg = 0;
    Msales.winThat = undefined;
    Msales.dgType = undefined;

    var list = $(":checkbox");
    var tmp = 0;
    for (var i = 1; i < list.length; i++) {
        var td = $(list[i]).closest("td");
        if (td.hasClass("datagrid-row-selected")) {
            tmp = i;
        }
    }
    if (tmp == 0) {
        $(list[1]).closest("td").trigger("click");
    }

    $(":checkbox").attr("tabindex", -1);
};

Array.prototype.contains = function (needle) {
    for (var i in this) {
        if (this[i] == needle) return true;
    }
    return false;
};

//删除
Msales.remove = function () {
    var sels = Msales.dtable.datagrid('getChecked');
    if (sels.length == 0) {
        $yd.alert('请选中记录');
        return;
    }
    var ids = [];
    $.each(sels, function (i, n) {
        ids.push(n['skuId']);
    });

    $.each(ids, function (i, n) {
        var rows = Msales.dtable.datagrid('getRows');
        for (var ii = 0; ii < rows.length; ii++) {
            if (rows[ii].skuId == n) {
                Msales.dtable.datagrid('deleteRow', ii);
                break;
            }
        }
    });
    Msales.caculate();

    var tds = $(".datagrid-row-selected");
    if (tds.length == 0) {
        var checks = $(":checkbox");
        if (checks.length > 1) {
            $(checks[1]).closest("td").trigger("click");
        }
    }
};

Msales.isEmpty = function (value) {
    if (value == undefined || value == null || value == "") {
        return true;
    }
    return false;
};
Msales.save0 = function () {
    Msales.save(0);
};
Msales.save1 = function () {
    Msales.save(1);
};
Msales.save = function (type) {
    if(Msales.isEmpty($('#cusId').combogrid('getValue'))){
        $yd.alert("请选择客户");
        return false;
    }
    //结束编辑状态
    if (Msales.editIndex != undefined && Msales.editIndex != -1) {
        Msales.dtable.datagrid('endEdit', Msales.editIndex);
    }

    $('#myForm').form('submit', {
        url: Msales.uEdit,
        onSubmit: function () {
            var isValid = $(this).form('validate');//只能校验处于编辑状态的栏位
            if (!isValid) {
                return isValid;
            }

            //校验数据
            var rows = Msales.dtable.datagrid("getRows");
            if (rows.length == 0) {
                $yd.alert("请添加商品");
                return false;
            }

            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                if (Number(row.count) > Number(row.skusNum)) {
                    $yd.alert("第" + (i + 1) + "行：销售数量不能大于当前库存");
                    return false;
                }
            }
            //
            // if (type == 1) {
            //     for (var i = 0; i < rows.length; i++) {
            //         var row = rows[i];
            //         var house = row.house;
            //         // if (Msales.isEmpty(house)) {
            //         //     $yd.alert("第" + (i + 1) + "行：未配置仓库/库位");
            //         //     return false;
            //         // }
            //         var total = 0;
            //         var arr = house.split(",");
            //         for (var j = 0; j < arr.length; j++) {
            //             total += Number(arr[j].split("_")[6]);
            //         }
            //         // if (total != row.count) {
            //         //     $yd.alert("第" + (i + 1) + "行：出库总数量必须等于销售数量");
            //         //     return false;
            //         // }
            //     }
            // }

            // if (Number($("#payFee").val()) > Number($("#totalFee").val())) {
            //     $yd.alert("本次付款金额不能大于应付总额！", function () {
            //         $("#payFee").numberbox("setValue", 0);
            //     });
            //     return false;
            // }

            //封装数据
            $("#type").val(type);
            $("#goods").val(JSON.stringify(rows));
            return isValid;
        },
        success: function (data) {
            var d = $.parseJSON(data);
            if (d.code == 0) {
                $yd.alert("操作成功", function () {
                    window.location.reload();
                });
            }
        }
    });
};

// 处理按钮
Msales.btn = function () {
    var sb = new $yd.SearchBtn($(Msales.obtn));
    sb.create('repeat red', '重置（Shift+R）', Msales.refresh);
    sb.create('save green', '生单出库（Shift+S）', Msales.save1);
    sb.create('save green', '生单（Shift+A）', Msales.save0);
};
Msales.keyDown = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (!e) {
        return;
    }
    // console.log("add.js")
    // if(e.keyCode==9) {
    //     if (e.preventDefault) {
    //         e.preventDefault();
    //     }
    //     else {
    //         e.returnValue = false;
    //     }
    // }
};
Msales.keyUp = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (!e) {
        return;
    }
    if (e.keyCode == 13 && Msales.dgType == "goods") {
        Msales.saveDgGoods();
    } else if (e.keyCode == 13 && Msales.dgType == "house") {
        Msales.saveDgHouse();
    }
    if (Msales.isDg != 0 && e.keyCode == 27 && Msales.winThat) {//ESC
        Msales.winThat.close();
    }
    if (Msales.isDg == 0) {
        if (e.keyCode == 45) {//insert
            Msales.plus();
        }
        if (e.keyCode == 46) {//del
            Msales.remove();
        }
        if (e.keyCode == 32) {//space
            var tds = $(".datagrid-row-selected");
            if (tds.length > 0) {
                var check = $(tds).find(":checkbox")[0];
                $(check).trigger("click");
            }
        }
        if (e.shiftKey && e.keyCode == 83) {
            Msales.save(1);//生单入库：Shfit + A
        }
        if (e.shiftKey && e.keyCode == 65) {
            Msales.save(0);//生单: Shift + S
        }
        if (e.shiftKey && e.keyCode == 82) {
            Msales.refresh();
        }
    }
};
Msales.init = function () {
    //默认值
    $("input[name='orderTime']").datebox({
        required: true,
        editable: false,
        value: new Date().getFullYear() + "-" + (new Date().getMonth() + 1) + "-" + new Date().getDate()
    });
    $("input[name='orderType']").combobox({
        url: "/sysDict/sale_type",
        panelHeight: 'auto',
        required: true,
        valueField: 'id',
        textField: 'text',
        editable: false,
        onLoadSuccess: function () {
            var d = $(this).combobox("getData");
            $(this).combobox("setValue", d[0].value);
        }
    });

    $("input[name='payStatus']").combobox({
        url: "/sysDict/purchase_next_status",
        panelHeight: 'auto',
        valueField: 'id',
        textField: 'text',
        editable: false,
        onLoadSuccess: function () {
            var d = $(this).combobox("getData");
            $(this).combobox("setValue", d[0].id);
        },
    });

    $("input[name='payType']").combobox({
        url: "/sysDict/pay_type",
        panelHeight: 'auto',
        editable: false,
        required: true,
        valueField: 'id',
        textField: 'text',
        onLoadSuccess: function () {
            var d = $(this).combobox("getData");
            $(this).combobox("setValue", d[0].value);
        }
    });

    new $yd.combogrid('#cusId', function (row) {
        if (row) {
            $("#cusId").val(row.id);
            $("#cusName").textbox("setValue", row.contactor);
            $("#cusTel").textbox("setValue", row.tel);
            $("#cusAddr").textbox("setValue", row.addr);
        } else {
            $("#cusId").val("");
            $("#cusName").textbox("setValue", "");
            $("#cusTel").textbox("setValue", "");
            $("#cusAddr").textbox("setValue", "");
        }
    }).addCol('name', '名称')
        .addCol('contactor', '联系人')
        .addCol('tel', '联系电话')
        .load('/wRelativeUnit/list?rproperty=1');

    //鼠标点击页面任何地方，表格编辑结束编辑状态
    document.onclick = Msales.mouseClick;

    //快捷键
    document.onkeydown = Msales.keyDown;
    document.onkeyup = Msales.keyUp;

    setTimeout("$('#orderTime').focus()", 500);
    $("a").attr("tabindex", -1);
    $(":checkbox").attr("tabindex", -1);
};
Msales.mouseClick = function (e) {
    e = window.event || e; // 兼容IE7
    var obj = $(e.srcElement || e.target);

    if (Msales.isDg == 0 && !$(obj).hasClass("datagrid-cell") && !$(obj).hasClass("datagrid-row-over")) {
        if (Msales.editIndex != -1) {
            Msales.dtable.datagrid('endEdit', Msales.editIndex);
            Msales.editIndex = -1;
            Msales.caculate();
        }
    }
};
$(function () {
    Msales.obtn = '#mSales_btn';
    Msales.dg(); // 数据表格
    Msales.btn(); // 初始化按钮
    Msales.init(); // 数据表格
});